/* ==================================================================   
 * Created [2009-4-27 下午11:32:55] by Jon.King 
 * ==================================================================  
 * TSS 
 * ================================================================== 
 * mailTo:jinpujun@hotmail.com
 * Copyright (c) Jon.King, 2009-2012 
 * ================================================================== 
 */

package com.jinhe.tss.cms.action;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.jinhe.tss.cms.CMSConstants;
import com.jinhe.tss.cms.entity.Channel;
import com.jinhe.tss.cms.entity.WordsFilter;
import com.jinhe.tss.cms.entity.permission.ChannelPermissionsFull;
import com.jinhe.tss.cms.entity.permission.ChannelResourceView;
import com.jinhe.tss.cms.helper.translator.ChannelCanSelectTranslator;
import com.jinhe.tss.cms.service.IChannelService;
import com.jinhe.tss.cms.workflow.WorkFlow;
import com.jinhe.tss.cms.workflow.WorkFlowManager;
import com.jinhe.tss.component.dynproperty.support.IRemotePropertyService;
import com.jinhe.tss.component.support.web.webwork.ProgressActionSupport;
import com.jinhe.tss.core.exception.BusinessException;
import com.jinhe.tss.core.util.EasyUtils;
import com.jinhe.tss.core.util.XMLDocUtil;
import com.jinhe.tss.core.web.dispaly.tree.ITreeTranslator;
import com.jinhe.tss.core.web.dispaly.tree.LevelTreeParser;
import com.jinhe.tss.core.web.dispaly.tree.TreeEncoder;
import com.jinhe.tss.core.web.dispaly.xform.XFormEncoder;
import com.jinhe.tss.um.permission.PermissionHelper;

public class SiteAction extends ProgressActionSupport {
	private static final long serialVersionUID = 5793599083683435652L;

	private IChannelService channelService;
	private IRemotePropertyService propertyService;
    
    private Long    siteId;			//站点ID
    private String  action;			//功能名
    private Long    channelId;		//栏目ID
    private Long    resourceId;		//资源id
    private Integer isSite;         //标记值   "1"-站点;"0"-栏目
    private Long    id;
	private String  shieldWords;
	private String  forbidWords;
    
    private Channel channel = new Channel();

    /**
     * 获得站点和栏目树(包括所有的树节点过滤情况)
     */
    public String getSiteAll() {
        TreeEncoder treeEncoder = null;
		if("distributeArticle".equals(action) || "reshipArticle".equals(action)
                || "moveArticle".equals(action) || "copyArticle".equals(action)){
            
            Object[] object = channelService.selectCanAddArticleParentChannels();
			treeEncoder = new TreeEncoder(object[0], new LevelTreeParser());
			treeEncoder.setRootCanSelect(false);
			treeEncoder.setTranslator(new ChannelCanSelectTranslator((String) object[1], channelId));
            
		}
		else if("moveChannel".equals(action) || ("copyChannel").equals(action)){
            Object[] object = channelService.selectCanAddChannelParentChannels();
			treeEncoder = new TreeEncoder(object[0], new LevelTreeParser());
			treeEncoder.setRootCanSelect(false);
			
			final List<Channel> selectedList = channelService.getChannelTreeDown(channelId);
			
			final List<String> canAddChannelIds = Arrays.asList(((String) object[1]).split(",")) ;
			
			//  树栏目是否可选 转换器 (专门为移动节点时的目标树结构用，移动节点的子节点都不可选)
			treeEncoder.setTranslator(new ITreeTranslator() {
			    public Map<String, Object> translate(Map<String, Object> attributes) {
			        Object channelId = attributes.get("id");
			        for ( Channel channel : selectedList ) {
			            if (channelId.equals(channel.getId())) {
			                attributes.put("canselected", "0");
			            }
			        }
			        
			        if( !canAddChannelIds.contains(String.valueOf(channelId)) ){
			        	attributes.put("canselected", "0");
			        }
			        return attributes;
			    }
			});
            
		}else{
			treeEncoder = new TreeEncoder(channelService.getAllSiteChannelList(), new LevelTreeParser());
		}
        return print("SiteTree",treeEncoder);      
    }
    
    /**
     * 	新建站点
     */
    public String saveSite(){
        //新增的站点只有公有站点
        channel.setIsSite(isSite);
        channel.setParentId(CMSConstants.HEAD_NODE_ID);
        
        Integer workflowId = channel.getWorkflowId();
        WorkFlow flow = WorkFlowManager.getInstance().getWorkFlow(workflowId);
        if(flow == null) {
            throw new BusinessException("指定的文章工作流不存在。");
        }
        channel.setWorkflowName(flow.getName());
        
        channelService.createSite(channel);

        return doAfterSave(true, channel, "SiteTree");
    }
    
    /**
     *  更新站点信息
     */
    public String updateSite(){
        channel.setIsSite(isSite);
        channelService.updateSite(channel);
        return printSuccessMessage("修改成功！");
    }
    
    /**
     *  获得站点的详细信息
     */
    public String getSiteDetail() {
        if ( isCreateNew() ) {
            channel = new Channel();
            channel.setDocPath("docDir");
            channel.setImagePath("imgDir");
        } 
        else {
            channel = channelService.getSiteById(siteId);
        }
        
        Map<String, String> map = propertyService.getXFormTemplate("site","baseXForm4Site");
        Object siteXForm = map.get(CMSConstants.SITE_BASE_INFO_TAB_KEY);
        if( siteXForm == null ){
        	throw new BusinessException("站点表单布局尚未设置,请转到动态属性进行设置.");
        }
        XFormEncoder xEncoder = new XFormEncoder(XMLDocUtil.dataXml2Doc((String) siteXForm), channel, false, false);
        String[] objs = WorkFlowManager.getInstance().getWorkFlowCodeAndNames();
        xEncoder.setColumnAttribute("workflowId", "editorvalue", objs[0]);
        xEncoder.setColumnAttribute("workflowId", "editortext", objs[1]);
        return print("SiteInfo", xEncoder);
    }

    /**
     *  逻辑删除站点成功
     */
    public String deleteSite(){
        channelService.deleteChannel(siteId);
        return printSuccessMessage("删除成功！");
    }
    /**
     *  启用栏目
     */
    public String startSite(){
        channelService.startChannel(id);
        return printSuccessMessage("启用成功！");
    }
    
    /**
     * 启用站点下所有栏目
     */
    public String startAll(){
        channelService.startSiteAll(id);
        return printSuccessMessage("启用成功！");
    }
    /**
     * 停用站点
     */
    public String stopSite(){
        channelService.stopSite(id);
        return printSuccessMessage("停用成功！");  
    }

    /**
     * 复制站点(站点和栏目分开传给前台进行处理)
     */
    public String copySite(){
        List<Channel> list = channelService.copyChannel(siteId, CMSConstants.HEAD_NODE_ID);
        TreeEncoder treeEncoder = new TreeEncoder(list, new LevelTreeParser());
        treeEncoder.setNeedRootNode(false);
        return print("SiteTree", treeEncoder);
    }
    
    /**
     *  根据资源id来获取操作权限
     */
    public String getOperatorByResourceId(){
        List<String> list = PermissionHelper.getInstance().getOperationsByResource(resourceId, 
                ChannelPermissionsFull.class.getName(), ChannelResourceView.class);
        
        String permissionAll = "p1,p2," + EasyUtils.list2Str(list) + "cd1,cd2,cd3,cd4,cd5,ca1,ca2,ca3,ca4,ca5";
        return print("Operation", permissionAll);
    }
    
    /**
     * 初始化过滤信息XFrom
     */
    public String initWordsFilterXForm(){
    	WordsFilter filter = channelService.getWordsFilterInfo(siteId);
    	if( filter == null ) {
    		filter = new WordsFilter();
    	}
    	
    	XFormEncoder xEncoder = new XFormEncoder(CMSConstants.XFORM_TEMPLATE_WORDS_FILTER, filter);
    	return print("FilterInfo", xEncoder);
    }
    
    /**
     * 保存词组过滤信息
     */
	public String saveWordsFilterInfo(){
		channelService.saveWordsFilter(shieldWords, forbidWords, siteId);
        return printSuccessMessage("操作成功！");
	}

    public void setIsSite(Integer isSite) {
        this.isSite = isSite;
    }
	public void setShieldWords(String shieldWords) {
		this.shieldWords = shieldWords;
	}
	public void setForbidWords(String forbidWords) {
		this.forbidWords = forbidWords;
	}  
    public void setId(Long id) {
        this.id = id;
    }
    public Channel getChannel() {
        return channel;
    }
    public void setSiteId(Long siteId) {
        this.siteId = siteId;
    }
    public void setResourceId(String resourceId) {
        if("_rootId".equals(resourceId)){
            this.resourceId = CMSConstants.HEAD_NODE_ID;
        }else{
            this.resourceId = new Long(resourceId);
        }
    }
    public void setAction(String action) {
        this.action = action;
    }
    public void setChannelId(Long channelId) {
        this.channelId = channelId;
    }
    
    public void setPropertyService(IRemotePropertyService propertyService) {
        this.propertyService = propertyService;
    }
    public void setChannelService(IChannelService channelService) {
        this.channelService = channelService;
    }
}